package org.xilin

class StudentController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def authenticateService
    def semesterService

    def role = ''
    def beforeInterceptor = {
        role = authenticateService.ifAllGranted('ROLE_USER,ROLE_ADMIN')? 'any' : ''
    }

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        render(template: "list", model: [studentInstanceList: Student.list(), studentInstanceTotal: Student.count()])
    }

    def create = {
        log.debug("create")
        def studentInstance = new Student()
        studentInstance.properties = params
        render( template: 'create', model:[studentInstance: studentInstance])
    }

    def save = {
        log.debug("save")
        def studentInstance = null
        if (params.id) {
            studentInstance = Student.get(params.id)
            studentInstance.properties = params
        }
        else {
            studentInstance = new Student(params)
        }
        def familyInstance = Family.findByUserId(params.userId)
        if(!params.id && familyInstance) {
            familyInstance.addToStudents(studentInstance)
        }
        if (studentInstance.save(flush: true)) {
//            flash.message = "${message(code: 'default.saved.message', args: [message(code: 'student.label', default: 'Student'), studentInstance.id])}"
        }
        if (!studentInstance.validate()) {
            studentInstance.errors.allErrors.each {
                log.debug(it)
            }
            flash.message = "Missing required data"
            render(template: params.view, model: [studentInstance: studentInstance])
            return
        }
        if(!params.id && familyInstance) {
            familyInstance.save(flush: true)
        }
        //render(template: params.view, model: [courseInstance: courseInstance])
        chain(controller: "family", action: "studentList", params:[id: params.userId])
    }

    def show = {
        def studentInstance = Student.get(params.id)
        if (!studentInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), params.id])}"
            redirect(action: "list")
        }
        else {
            //            [studentInstance: studentInstance]
            render (template:'show', model:[studentInstance: studentInstance])
        }
    }

    def edit = {
        def studentInstance = Student.get(params.id)
        if (!studentInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), params.id])}"
            redirect(action: "list")
        }
        else {
            render(template: "edit", model: [studentInstance: studentInstance])
//            return [studentInstance: studentInstance]
        }
    }

    def update = {
        def studentInstance = Student.get(params.id)
        if (studentInstance) {        
            studentInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'student.label', default: 'Student')] as Object[], "Another user has updated this Student while you were editing")
            render(view: "edit", model: [studentInstance: studentInstance])
            return
              
            studentInstance.properties = params
            if (!studentInstance.hasErrors() && studentInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'student.label', default: 'Student'), studentInstance.id])}"
                redirect(action: "show", id: studentInstance.id)
            }
            else {
                render(view: "edit", model: [studentInstance: studentInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        Student studentInstance = Student.get(params.id)
        if (studentInstance && !studentInstance.classes) {
            try {
                studentInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'student.label', default: 'Student'), params.id])}"
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'student.label', default: 'Student'), params.id])}"
            }
        } else if(studentInstance && studentInstance.classes) {
            flash.message = "Cannot delete student" + studentInstance + ". he/she has courses."
        } else {        // also if student has courses
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), params.id])}"
        }
        chain(controller: "family", action: "studentList", params:[id: params.userId])
    }

    def adminList = {
        render(template: "adminList", model: [instanceList: Student.list(), studentInstanceTotal: Student.count()])
    }

    def adminCreate = {
        def studentInstance = null

        if (params.id) {
            studentInstance = Student.get(params.id)
        }
        else {
            studentInstance = new Student()
            studentInstance.properties = params
        }
        render(template: "adminCreate", model: [studentInstance: studentInstance])
    }

    def adminSave = {
        def studentInstance = null

        if (params.id) {
            studentInstance = Student.get(params.id)
            studentInstance.properties = params
        }
        else {
            studentInstance = new Student(params)
        }

        if (!studentInstance.validate()) {
            studentInstance.errors.allErrors.each {
                log.debug(it)
            }
            flash.message = "Missing required data for Student"
            render(template: params.view, model: [studentInstance: studentInstance])
            return
        }

        if (studentInstance.save(flush:true)) {
            studentInstance.refresh()
            redirect(action: "adminList")
        }
        else {
            studentInstance.errors.allErrors.each {
                log.debug(it)
            }
            flash.message = "Missing required data for Student"
            render(template: params.view, model: [studentInstance: studentInstance])
        }
    }

    def adminDelete = {
        def studentInstance = Student.get(params.id)
        if (studentInstance) {
            try {
                studentInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'student.delete.label', default: 'Student deleted'), params.id])}"
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'family.delete.label', default: 'Failed to delete student'), params.id])}"
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'family.label', default: 'Family'), params.id])}"
       }

       redirect(action: "adminList")
    }

  def adminAddClass = {
      def studentInstance = null

      if (params.id) {
          studentInstance = Student.get(params.id)
          def courseList = semesterService.getListBySemester(Course)
          def selectedCourseList = TheClass.findAllByStudent(studentInstance)
          render(template: "adminAddClass", model: [studentInstance: studentInstance, courseInstanceList: courseList, selectedCourseList: selectedCourseList])
      }
  }

    def adminAddClassToStudent = {
        def studentInstance = null
      
        if (params.id) {
            studentInstance = Student.get(params.id)
            TheClass.unlink(studentInstance)

            def courseIdList = params.courseIdList?.split(',')
            courseIdList?.each {
                TheClass.link(Course.get(it as int), studentInstance)
            }
          
            render(template: "adminAddClass", model: [studentInstance: studentInstance])
        }
      
    }

    def adminAddBook = {
        def studentInstance = null

        if (params.id) {
            studentInstance = Student.get(params.id)
            def bookList = Book.list()
            def selectedCourseList = TheClass.findAllByStudent(studentInstance)
            render(template: "adminAddBook", model: [studentInstance: studentInstance, bookInstanceList: bookList, selectedCourseList: selectedCourseList])
        }
    }

    def adminAddBookToStudent = {
        def studentInstance = null

        if (params.id) {
            studentInstance = Student.get(params.id)
            // delete books
            studentInstance.books.clear()
          
            println ">> params.bookIdList = " + params.bookIdList
            def bookIdList = params.bookIdList?.split(',')
            bookIdList?.each {
                // add book
                studentInstance.addToBooks(Book.get(it))
            }

            render(template: "adminAddClass", model: [studentInstance: studentInstance])
        }
    }

}
